<?php
// 应用公共文件

use app\common\service\utils\RetCodeUtils;
use think\facade\Config;

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use think\File;
use Overtrue\Pinyin\Pinyin;
use think\facade\Cache;



/**
 * 获取当前日期时间
 * 
 * @param string $format 格式，默认Y-m-d H:i:s
 *
 * @return string
 */
function datetime($format = 'Y-m-d H:i:s')
{
    return date($format);
}

/**
 * 时间戳 转成库龄格式
 * 
 * @param string $format 格式，默认Y-m-d H:i:s
 *
 * @return string
 */
function diffDate($date1,$date2)
{
    $datetime1 = new \DateTime(date('Y-m-d',$date1));
    $datetime2 = new \DateTime(date('Y-m-d',$date2));
    $interval = $datetime1->diff($datetime2);
    $time['y']         = $interval->format('%Y'); // 两个时间相差总年数
    $time['m']         = $interval->format('%m'); // 两个时间相差总月数
    $time['d']         = $interval->format('%d');// 两个时间相差总天数
    $time['h']         = $interval->format('%H');
    $time['i']         = $interval->format('%i');
    $time['s']         = $interval->format('%s');
    $time['a']         = $interval->format('%a');    // 两个时间相差总天数
    return $time['y'].'年'.$time['m'].'月'.$time['d'].'天';
}


//get请求
function crul_get($url,$headers,$bodyParams){
     $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 60);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //验证curl对等证书(一般只要此项)
//    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); //检查服务器SSL证书中是否存在一个公用名
//    curl_setopt($ch, CURLOPT_SSLVERSION, 0);  //传递一个包含SSL版本的长参数。
    curl_setopt($ch, CURLOPT_HTTPHEADER, array_map(function ($v, $k) {
        return $k . ': ' . $v;
    }, array_values($headers), array_keys($headers)));

    if (in_array('GET', array('POST', 'PUT', 'PATCH'), true)) {
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($bodyParams));
    }

    $data = curl_exec($ch);
    $error = curl_error($ch);
    curl_close($ch);
    return $data;

}

if (!function_exists('get_first_letter')) {
    /**
     * 获取中文字符串的首字母
     * @param string $chinese 中文字符串
     * @param bool $onlyFirstChar 是否只返回第一个字的首字母
     * @return string
     */
    function get_first_letter(string $chinese, bool $onlyFirstChar = false): string
    {
        $pinyin = new Pinyin();
        
        // 获取所有字的首字母（返回数组，如 ['N', 'H', 'S', 'J']）
        $letters = $pinyin->abbr($chinese);
        
        if ($onlyFirstChar) {
            return $letters[0] ?? ''; // 只返回第一个字的首字母
        }
       
        return implode('', $letters->toArray()); // 拼接成字符串，如 "NHSJ"
    }
}
function  crul($sysParams){
         $baseUrl='http://api.dhgate.com/dop/router';           
      // 构建查询字符串，并进行URL编码
      $queryString = http_build_query($sysParams);

      $requestUrl = $baseUrl . '?' . $queryString; 

      $ch = curl_init();
      curl_setopt_array($ch, [
        CURLOPT_URL => $requestUrl,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => ['Content-Type: application/x-www-form-urlencoded']
      ]);

      $response = curl_exec($ch);
      $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
      $error = curl_error($ch);
      curl_close($ch);
   
     if ($response === false) {
        echo json_encode(['error' => 'cURL Error: ' . $error]);
      } elseif ($httpCode !== 200) {
        return json_decode($response,true);
      } else {
       return json_decode($response,true);
      }
}



function post_crul($sysParams) {
    $baseUrl = 'http://api.dhgate.com/dop/router';
    
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $baseUrl,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,  // 设置为POST请求
        CURLOPT_POSTFIELDS => http_build_query($sysParams),  // POST数据
        CURLOPT_HTTPHEADER => ['Content-Type: application/x-www-form-urlencoded']
    ]);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);
    curl_close($ch);

    if ($response === false) {
        echo json_encode(['error' => 'cURL Error: ' . $error]);
    } elseif ($httpCode !== 200) {
        return json_decode($response, true);
    } else {
        return json_decode($response, true);
    }
}

//从图片URL获取图片，添加斜体文字水印，并转为Base64
function addSlantedWatermarkToImageUrl($imageUrl, $watermarkText, $fontSize = 20, $fontColor = '000000', $opacity = 50, $angle = 30, $spacing = 150) {
    
    $savePaths = root_path() . '/public/Uploads/img/'.date('Ymd');
    if (!is_dir($savePaths)) {
        // 目录不存在，尝试创建目录
        if (!mkdir($savePaths, 0755, true)) {
            echo '无法创建目录：'.$savePaths.',请联系技术人员开放目录权限';
        }
    }
    // 1. 从URL获取图片
    $imageData = file_get_contents($imageUrl);
    if ($imageData === false) {
        throw new Exception("无法从URL获取图片");
    }
    
    // 2. 创建图像资源
    $image = imagecreatefromstring($imageData);
    if (!$image) {
        throw new Exception('无法创建图像资源');
    }
    
    // 3. 获取图片尺寸
    $width = imagesx($image);
    $height = imagesy($image);
    
    // 4. 设置水印颜色和透明度
    $color = imagecolorallocatealpha(
        $image,
        hexdec(substr($fontColor, 0, 2)),
        hexdec(substr($fontColor, 2, 2)),
        hexdec(substr($fontColor, 4, 2)),
        127 * (1 - $opacity / 100)
    );
    
    // 5. 选择字体(需要确保服务器上有该字体文件)
    $fontFile = '/www/wwwroot/ErpApi/public/fonts/祥南行書體.TTF'; // 替换为你的字体文件路径
    if (!file_exists($fontFile)) {
        throw new Exception('字体文件不存在');
    }
    
    // 6. 计算单个水印文本的尺寸
    $textBox = imagettfbbox($fontSize, $angle, $fontFile, $watermarkText);
    $textWidth = max($textBox[2], $textBox[4]) - min($textBox[0], $textBox[6]);
    $textHeight = max($textBox[3], $textBox[5]) - min($textBox[1], $textBox[7]);
    
    // 7. 计算需要多少个水印才能覆盖整个图片
    $cols = ceil($width / ($textWidth + $spacing*1.5)) + 1;
    $rows = ceil($height / ($textHeight + $spacing*1.1)) + 1;
    
    // 8. 在整个图片上平铺斜体水印
    for ($i = -$rows; $i < $rows; $i++) {
        for ($j = -$cols; $j < $cols; $j++) {
            $x = $j * ($textWidth + $spacing*1.5);
            $y = $i * ($textHeight + $spacing*1.8);
            
            // 添加斜体水印
            imagettftext($image, $fontSize, $angle, $x, $y, $color, $fontFile, $watermarkText);
        }
    }
    
    // 9. 输出为Base64
    // 7. 生成文件名（如果未提供）
    if (empty($filename)) {
        $filename = 'watermarked_' . md5($imageUrl . time()) . '.jpg';
    } else {
        // 确保文件名有扩展名
        if (pathinfo($filename, PATHINFO_EXTENSION) === '') {
            $filename .= '.jpg';
        }
    }
    
    // 8. 保存图片
    $savePath = rtrim($savePaths, '/') . '/' . $filename;
    
    // 根据扩展名选择保存格式
    $extension = strtolower(pathinfo($savePath, PATHINFO_EXTENSION));
    switch ($extension) {
        case 'jpg':
        case 'jpeg':
            $success = imagejpeg($image, $savePath, 90); // 90%质量
            break;
        case 'png':
            $success = imagepng($image, $savePath);
            break;
        case 'gif':
            $success = imagegif($image, $savePath);
            break;
        default:
            imagedestroy($image);
            throw new Exception("不支持的图片格式: $extension");
    }
    
    imagedestroy($image);
    
    if (!$success) {
        throw new Exception("无法保存图片到: $savePath");
    }
    $normalizedPath = preg_replace('#/+#', '/', $savePath);
$relativePath = str_replace('/www/wwwroot/ErpApi/public', '', $normalizedPath);

// 输出: /Uploads/img/20250825/watermarked_08ce07e177cd3aea06a18b0a94423084.jpg

    return $relativePath;
}


/**
 * 成功返回

 * @param array  $data 数据
 * @param string $msg  提示
 * @param int    $code 返回码
 * 
 * @return json
 */
function success($data = [])
{  
    print_r( json_encode($data, JSON_UNESCAPED_UNICODE));
}


    //截断函数
    function get_sub_content($str, $start, $end){
        if ( $start == '' || $end == '' ){

            return;
        }
        $str = explode($start, $str);
        $str = explode($end, $str[1]);
        $strs=[];
        if(strpos($str[0], 'offer-type') !== false && strlen($str[1])>20){
            $strs=$str[1];
        }elseif(strpos($str[0], 'offer-type') !== false && strlen($str[1])<20){
              $strs=$str[0];
        }elseif(strpos($str[0], 'offer-type') == false ){
            $strs=$str[0];
        }    
        return  $strs;
    }
    /**
 * 使用curl获取远程数据
 * @param  string $url url连接
 * @return string      获取到的数据
 */
    function curl_get_contents($url, $post = 0, $postFields = '', $timeOut = 5, $header=array() ,$ssl = 0){
        $ch=curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);                //设置访问的url地址
        curl_setopt($ch, CURLOPT_ENCODING, "");
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,$ssl);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,$ssl);

        if($post && $postFields)
        {
            curl_setopt($ch,CURLOPT_POST,TRUE);
            curl_setopt($ch,CURLOPT_POSTFIELDS,$postFields);
        }
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_HEADER, FALSE);               //是否显示头部信息
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeOut);               //设置超时

        curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);   //用户访问代理 User-Agent
        curl_setopt($ch, CURLOPT_REFERER,$_SERVER['HTTP_HOST']);        //设置 referer

        //curl_setopt($ch,CURLOPT_FOLLOWLOCATION,1);          //跟踪301
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);        //返回结果
        $r=curl_exec($ch);
        curl_close($ch);
        return $r;
    }


  /**
 * 有道英文翻译的
 * @param  string $url url连接
 * @return string      获取到的数据 */
/******************************有道翻译****************************************** */
 function do_call($url, $method, $header, $param, $expectContentType, $timeout = 3000)
{
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    // curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 不验证对等证书
    // curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); // 不验证主机名
    if (!empty($header)) {
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
    }
    $data = http_build_query($param);
    if ($method == 'post') {
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    } else if ($method == 'get') {
        $url = $url . '?' . $data;
    } else {
        print 'http method not support';
        return null;
    }
    curl_setopt($curl, CURLOPT_URL, $url);
    $r = curl_exec($curl);
    $contentType = curl_getinfo($curl, CURLINFO_CONTENT_TYPE);
    if (strpos($contentType, $expectContentType) === false) {
        echo $r;
        $r = null;
    }
    curl_close($curl);
    return $r;
}
function add_auth_params($param, $appKey, $appSecret)
{
    if (array_key_exists('q', $param)) {
        $q = $param['q'];
    } else {
        $q = $param['img'];
    }
    $salt = create_uuid();
    $curtime = strtotime("now");
    $sign = calculate_sign($appKey, $appSecret, $q, $salt, $curtime);
    $param['appKey'] = $appKey;
    $param['salt'] = $salt;
    $param["curtime"] = $curtime;
    $param['signType'] = 'v3';
    $param['sign'] = $sign;
    return $param;
}

function create_uuid()
{
    $str = md5(uniqid(mt_rand(), true));
    $uuid = substr($str, 0, 8) . '-';
    $uuid .= substr($str, 8, 4) . '-';
    $uuid .= substr($str, 12, 4) . '-';
    $uuid .= substr($str, 16, 4) . '-';
    $uuid .= substr($str, 20, 12);
    return $uuid;
}

function calculate_sign($appKey, $appSecret, $q, $salt, $curtime)
{
    $strSrc = $appKey . get_input($q) . $salt . $curtime . $appSecret;
    return hash("sha256", $strSrc);
}

function get_input($q)
{
    if (empty($q)) {
        return null;
    }
    $len = mb_strlen($q, 'utf-8');
    return $len <= 20 ? $q : (mb_substr($q, 0, 10) . $len . mb_substr($q, $len - 10, $len));
}
/******************************有道翻译 end****************************************** */
